package com.ticket.sass.admin.business.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ticket.sass.admin.business.DispatchBusiness;
import com.ticket.sass.admin.dto.output.dispatch.DispatchGuideOutput;
import com.ticket.sass.admin.dto.input.dispatch.DispatchHallConfigInput;
import com.ticket.sass.admin.dto.output.dispatch.HallDispatchListOutput;
import com.ticket.sass.admin.dto.input.dispatch.DispatchGuideSaveInput;
import com.ticket.sass.admin.dto.input.dispatch.DispatchGuideTypeInput;
import com.ticket.sass.admin.dto.input.dispatch.HallDispatchListInput;
import com.ticket.sass.admin.model.PageModel;
import com.ticket.sass.admin.service.impl.CommodityDispatchGuideServiceImpl;
import com.ticket.sass.admin.service.impl.CommodityDispatchHallServiceImpl;
import com.ticket.sass.admin.service.impl.HallServiceImpl;
import com.ticket.sass.admin.util.CinemaIdUtil;
import com.ticket.sass.admin.util.ModelUtil;
import com.ticket.sass.common.entity.tenant.CommodityDispatchGuideEntity;
import com.ticket.sass.common.entity.tenant.CommodityDispatchHallEntity;
import com.ticket.sass.common.entity.tenant.HallEntity;
import com.ticket.sass.common.entity.tenant.enums.CommodityDispatchMode;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author ywb
 * @date 2024-04-08 17:20
 */
@Slf4j
@Service
@AllArgsConstructor
public class DispatchBusinessImpl implements DispatchBusiness {
    final ModelUtil modelUtil;
    final HallServiceImpl hallService;
    final CommodityDispatchHallServiceImpl commodityDispatchHallService;
    final CommodityDispatchGuideServiceImpl commodityDispatchGuideService;
    
    @Override
    public void saveDispatchHallConfig(DispatchHallConfigInput input) {
        // 根据影厅ID查询是否已存在配置
        CommodityDispatchHallEntity existingConfig = commodityDispatchHallService.getOne(new QueryWrapper<CommodityDispatchHallEntity>().eq("hall_id", input.getHallId()));
        
        // 如果已存在配置，则进行更新操作；否则进行插入操作
        if (existingConfig != null) {
            // 更新操作
            existingConfig.setMode(CommodityDispatchMode.Companion.valueOf(input.getMode()));
            commodityDispatchHallService.updateById(existingConfig);
        } else {
            // 插入操作
            CommodityDispatchHallEntity newConfig = new CommodityDispatchHallEntity();
            newConfig.setHallId(input.getHallId());
            newConfig.setMode(CommodityDispatchMode.Companion.valueOf(input.getMode()));
            commodityDispatchHallService.save(newConfig);
        }
    }
    
    @Override
    public PageModel<HallDispatchListOutput> list(HallDispatchListInput input) {
        IPage<HallEntity> page = hallService.iPage(input);
        List<HallEntity> hallEntities = page.getRecords();
        
        // 获取所有影厅的ID
        List<Long> hallIds = hallEntities.stream().map(HallEntity::getId).collect(Collectors.toList());
        
        // 查询所有影厅对应的配送方式
        Map<Long, Short> dispatchModeMap = getDispatchModeByHallIds(hallIds);
        
        // 构造输出对象列表
        List<HallDispatchListOutput> outputs = new ArrayList<>();
        for (HallEntity hallEntity : hallEntities) {
            HallDispatchListOutput output = modelUtil.map(hallEntity, HallDispatchListOutput.class);
            Short mode = dispatchModeMap.getOrDefault(hallEntity.getId(), (short) 0);
            output.setMode(mode);
            outputs.add(output);
        }
        
        return new PageModel<>(page.getTotal(), outputs);
    }
    
    // 根据影厅ID列表查询配送方式，并以Map形式返回
    private Map<Long, Short> getDispatchModeByHallIds(List<Long> hallIds) {
        if (hallIds.size() == 0){
            return new HashMap<>();
        }
       
        List<CommodityDispatchHallEntity> dispatchHallEntities = commodityDispatchHallService.lambdaQuery()
            .in(CommodityDispatchHallEntity::getHallId, hallIds)
            .list();
        
        // 构造以影厅ID为键，配送方式为值的Map
        Map<Long, Short> dispatchModeMap = new HashMap<>();
        for (CommodityDispatchHallEntity dispatchHallEntity : dispatchHallEntities) {
            dispatchModeMap.put(dispatchHallEntity.getHallId(), dispatchHallEntity.getMode().getValue());
        }
        
        return dispatchModeMap;
    }
    
    
    @Override
    public void saveDispatchGuideById(DispatchGuideSaveInput input) {
        Long cinemaId = CinemaIdUtil.getCinemaIdFromRequest();
        
        // 查询影院对应的卖品配送提示指南
        QueryWrapper<CommodityDispatchGuideEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("cinema_id", cinemaId);
        queryWrapper.eq("mode", input.getMode());
        CommodityDispatchGuideEntity guideEntity = commodityDispatchGuideService.getOne(queryWrapper);
        
        if (guideEntity == null) {
            // 如果不存在，则新增
            guideEntity = new CommodityDispatchGuideEntity();
            guideEntity.setContent(input.getContent());
            guideEntity.setMode(CommodityDispatchMode.Companion.valueOf(input.getMode()));
            guideEntity.setCinemaId(cinemaId);
            // 其他字段赋值...
            
            commodityDispatchGuideService.save(guideEntity);
        } else {
            // 如果存在，则修改
            guideEntity.setContent(input.getContent());
            guideEntity.setMode(CommodityDispatchMode.Companion.valueOf(input.getMode()));
            // 其他字段赋值...
            
            commodityDispatchGuideService.updateById(guideEntity);
        }
    }

    
    @Override
    public DispatchGuideOutput getDispatchGuide(DispatchGuideTypeInput input) {
        Long cinemaId = CinemaIdUtil.getCinemaIdFromRequest();
        
        // 根据影院ID查询对应的卖品配送提示指南
        QueryWrapper<CommodityDispatchGuideEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("cinema_id", cinemaId);
        queryWrapper.eq("mode", input.getMode());
        CommodityDispatchGuideEntity guideEntity = commodityDispatchGuideService.getOne(queryWrapper);
        
        // 将查询到的实体转换为DTO对象并返回
        DispatchGuideOutput guideDTO = new DispatchGuideOutput();
        if (guideEntity != null) {
            guideDTO.setContent(guideEntity.getContent());
            guideDTO.setMode(guideEntity.getMode().getValue());
        }
        return guideDTO;
    }
}
